package middlewares

import (
	"context"
	"fmt"
	"gitee/kubehark/kubehark-gateway/pkg/oidc"
	"github.com/gin-gonic/gin"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"net/http"
	"strings"
)

// Oidc comment lint rebel
func Oidc(clientID, issuer, secret string) gin.HandlerFunc {
	return func(c *gin.Context) {
		authorization := strings.Split(c.Request.Header.Get("Authorization"), " ")
		if len(authorization) != 2 {
			c.JSON(http.StatusUnauthorized, metav1.Status{
				Code:    http.StatusUnauthorized,
				Message: "Bearer token required",
			})
			c.Abort()
			return
		}
		authorizationType := authorization[0]
		if authorizationType != "Bearer" {
			c.JSON(http.StatusUnauthorized, metav1.Status{
				Code:    http.StatusUnauthorized,
				Message: "Bearer token required",
			})
			return
		}

		authorizationToken := authorization[1]
		oidcApp, err := oidc.Setup(
			clientID,
			issuer,
			secret,
		)

		if err != nil {
			c.JSON(http.StatusUnauthorized, metav1.Status{
				Code:    http.StatusUnauthorized,
				Message: err.Error(),
			})
			c.Abort()
			return
		}

		idToken, err := oidcApp.GetVerifier().Verify(context.Background(), authorizationToken)

		if err != nil {
			c.JSON(http.StatusUnauthorized, metav1.Status{
				Code:    http.StatusUnauthorized,
				Message: err.Error(),
			})

			c.Abort()
			return
		}

		var claims oidc.Claims
		if err := idToken.Claims(&claims); err != nil {
			c.JSON(http.StatusUnauthorized, metav1.Status{
				Code:    http.StatusUnauthorized,
				Message: fmt.Sprintf("error decoding ID token claims: %v", err),
			})
			c.Abort()
			return
		}

		c.Set("user", claims.Name)
		c.Set("accessTokenHash", idToken.AccessTokenHash)
		fmt.Println(claims.Name)
		c.Next()
		return
	}

}
